package com.bird.generate.ddd.application

import cn.hutool.core.io.FileUtil
import com.bird.generate.ddd.application.pl.AddAggregateRootRequest
import com.bird.generate.ddd.domain.GenerateHandler
import jakarta.servlet.http.HttpServletResponse
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.File

/**
 * 生成应用层
 */
@Service
class GenerateApplication(
    private val generateHandler: GenerateHandler

) {
    @Value("\${download.path}")
    lateinit var path: String
    /**
     * 添加聚合根
     */
    @Transactional(rollbackFor = [Exception::class])
    fun addAggregateRoot(request: AddAggregateRootRequest): Long? {
        return generateHandler.addAggregateRoot(request.toAggregateRoot())
    }
    /**
     * 生成聚合根
     */
    fun generateAggregateRoot(aggregateRootId: Long) {
        generateHandler.generate(path, aggregateRootId)
    }

    fun download(name: String, response: HttpServletResponse) {
        val zip = generateHandler.download(path,name)
        response.contentType = "application/zip"
        response.setHeader("Content-Disposition", "attachment; filename=$name.zip")
        response.outputStream.use { outputStream ->
            outputStream.write(zip.readBytes())
            outputStream.flush()
        }
        FileUtil.del(zip)
    }


}